package club.gskj.gulimall.member.service.impl;

import club.gskj.common.utils.HttpUtils;
import club.gskj.gulimall.member.dao.MemberLevelDao;
import club.gskj.gulimall.member.entity.MemberLevelEntity;
import club.gskj.gulimall.member.exception.PhoneExistException;
import club.gskj.gulimall.member.exception.UserNameExistException;
import club.gskj.gulimall.member.vo.MemberLoginVo;
import club.gskj.gulimall.member.vo.MemberRegisterVo;
import club.gskj.gulimall.member.vo.SocialUser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.lang.reflect.Member;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import club.gskj.common.utils.PageUtils;
import club.gskj.common.utils.Query;

import club.gskj.gulimall.member.dao.MemberDao;
import club.gskj.gulimall.member.entity.MemberEntity;
import club.gskj.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDaol;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public void register(MemberRegisterVo memberRegisterVo) {

        MemberEntity memberEntity = new MemberEntity();

        // 获取默认会员等级id
        MemberLevelEntity level = memberLevelDaol.getDefaultLevel();
        // 会员等级id
        memberEntity.setLevelId(level.getId());
        // 检查手机号、用户名是否唯一
        this.checkPhoneUnique(memberRegisterVo.getPhone());
        this.checkPhoneUnique(memberRegisterVo.getUserName());
        memberEntity.setMobile(memberRegisterVo.getPhone());
        memberEntity.setUsername(memberRegisterVo.getUserName());

        // 设置密码加密MD5
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // 编码明文密码
        String encode = bCryptPasswordEncoder.encode(memberRegisterVo.getPassword());
        // 保存密文密码
        memberEntity.setPassword(encode);

        // 保存信息
        this.save(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        Integer username = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username > 0) {
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {

        // 账号
        String loginacct = vo.getLoginacct();

        // 明文 密码
        String password = vo.getPassword();

        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginacct).or().eq("mobile", loginacct);
        MemberEntity memberEntity = this.baseMapper.selectOne(queryWrapper);
        // 查询不到数据，返回null
        if (null == memberEntity) {
            return null;
        }

        // 查出数据，校验密码是否正确
        // 数据库 密文密码
        String dbPassword = memberEntity.getPassword();

        // 密码校验
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean matches = encoder.matches(password, dbPassword);
        // 校验成功，返回用户信息
        if (matches) {
            return memberEntity;
        }
        return null;
    }

    @Override
    public MemberEntity login(SocialUser vo) throws Exception {
        // 登陆、注册并用
        String uid = vo.getUid();

        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        if (memberEntity != null) {
            // 说明这个用户已经存在
            // 更新还用户的 access_token, expires_in

            MemberEntity entity = new MemberEntity();
            entity.setAccessToken(vo.getAccess_token());
            entity.setExpiresIn(vo.getExpires_in());
            entity.setId(memberEntity.getId());
            // 更新
            this.baseMapper.updateById(entity);

            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            return memberEntity;
        }
        // 该用户不存在，注册
        MemberEntity newMemberEntity = new MemberEntity();
        try {
            // 查询当前社交用户的基本信息
            Map<String, String> map = new HashMap<>();
            map.put("access_token", vo.getAccess_token());
            map.put("uid", vo.getUid());

            // 调用微博API接口， 获取微博用户基本信息
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "GET", new HashMap<String, String>(), map);

            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity());
                System.out.println(json);
                JSONObject jsonObject = JSON.parseObject(json);
                // 获取名称
                String name = jsonObject.getString("name");
                // 性别
                String gender = jsonObject.getString("gender");

                newMemberEntity.setUsername(name);
                newMemberEntity.setGender("m".equals(gender) ? 1 : 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 新创建的 用户要关联 社交用户信息
        newMemberEntity.setSocialUid(vo.getUid());
        newMemberEntity.setAccessToken(vo.getAccess_token());
        newMemberEntity.setExpiresIn(vo.getExpires_in());
        // 保存用户信息
        this.save(newMemberEntity);
        return newMemberEntity;
    }
}
